#include"../../inc/net/Acceptor.h"


#include<string>


using std::string;

namespace SE
{
    Acceptor::Acceptor(const string& ip, const unsigned short port)
    : _sock(), _addr(ip, port)
    {}

    Acceptor::Acceptor(const sockaddr_in& addr)
    : _sock(), _addr(addr)
    {}

    int Acceptor::Cfd()
    {
        sockaddr_in cli_addr = {0};
        socklen_t len = sizeof(sockaddr_in);
    
        int ret =  ::accept(_sock.fd(), (sockaddr*)&cli_addr, &len);
        if(-1 == ret)
            logError("accept err");
    
        return ret;
    }   

    int Acceptor::fd()
    {
        return _sock.fd();
    }

    void Acceptor::reuseAddr(bool flag)
    {
        int fflag = flag;
        int ret = ::setsockopt(_sock.fd(), 
        SOL_SOCKET, 
        SO_REUSEADDR, 
        &fflag, sizeof(fflag));
        if(-1 == ret)
            logError("setsockopt ADDR");
    }

    void Acceptor::reusePort(bool flag)
    {
        int fflag = flag;
        int ret = ::setsockopt(_sock.fd(), 
        SOL_SOCKET, 
        SO_REUSEPORT, 
        &fflag, sizeof(fflag));
        if(-1 == ret)
            logError("sersockopt PORT");
    }

    void Acceptor::Bind()
    {
        int ret = ::bind(_sock.fd(), 
        (sockaddr*)_addr.getAddr(), 
        sizeof(sockaddr));
        if(-1 == ret)
            logError("bind err");
    }

    void Acceptor::Listen(int size)
    {
        int ret = ::listen(_sock.fd(), size);
        if(-1 == ret)
            logError("listen err");
    }

    void Acceptor::Start()
    {
        reuseAddr(true);
        reusePort(true);
        Bind();
        Listen(128);
    }
}